<template>
  <view>
    <user-home v-if="!vuex_identity" @recruiClassifyChange="recruiClassifyChange" :document-list1="documentList1" :document-list2="documentList2" :recruit-list="recruitList" :product-list="productList" :status="status">
    </user-home>
    <server-home v-else :navList="serverNavList" :navList1="serverNavList1" :navList2="serverNavList2" :usuallyList="serverUsuallyList" :notice-list="noticeList"></server-home>
  </view>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      location: "",
      noticeList: [],
      documentList1: [],
      documentList2: [],
      recruitList: [],
      productList: [],
      status: "nomore",
      page: 1,
      pagesize: 3,
      refresh: true,
      serverNavList: [
        {
          image:
            "https://lzj.shandongweipai.com/uploads/20220223/77a9603d35c75e1d8a553be83eb00a1c.png",
          name: "提交案件",
          subname: "",
        },
      ],
      serverNavList1: [
        {
          url: "/pages/subpackages/mine/bidding/index",
          image:
            "https://lzj.shandongweipai.com/uploads/20220223/ccd81d4ee8cb3f9cf618dd4d4bcbe7b3.png",
          name: "我的竞标",
          subname: "平台派单 用户需求单",
        },
        {
          url: "/pages/subpackages/mine/order/order",
          image:
            "https://lzj.shandongweipai.com/uploads/20220223/6385329d0b0ed0088e7d7901d9e19894.png",
          name: "我的订单",
          subname: "用户购买服务",
        },
      ],
      serverNavList2: [
        {
          url: "/pages/subpackages/answer/answer",
          image:
            "https://lzj.shandongweipai.com/uploads/20220223/3ce19d9d01754dc6757b1c0091305fe4.png",
          name: "咨询抢答",
          subname: "极速咨询 电话咨询",
        },
        {
          url: "/pages/subpackages/answer/my",
          image:
            "https://lzj.shandongweipai.com/uploads/20220223/154935621d6816028f8481379ce0080d.png",
          name: "我的抢答",
          subname: "极速咨询 电话咨询",
        },
        {
          url: "/pages/subpackages/classify/recruit/index",
          image:
            "https://lzj.shandongweipai.com/uploads/20220223/ccd81d4ee8cb3f9cf618dd4d4bcbe7b3.png",
          name: "招聘专区",
          subname: "人才招聘 发布职位",
        },
        {
          url: "/pages/subpackages/classify/inquire/index",
          image:
            "https://lzj.shandongweipai.com/uploads/20220223/6385329d0b0ed0088e7d7901d9e19894.png",
          name: "打听发布",
          subname: "悬赏金",
        },
      ],
      serverUsuallyList: [
        {
          url: "/pages/subpackages/mine/resume/index",
          image: "/static/img/usually-item-01.png",
          name: "我的履历",
        },
        {
          url: "/pages/subpackages/mine/inquire/inquire",
          image: "/static/img/usually-item-02.png",
          name: "我的打听",
        },
        {
          url: "/pages/subpackages/mine/customer/customer",
          image: "/static/img/usually-item-03.png",
          name: "我的客户",
        },
        {
          url: "/pages/subpackages/mine/price/price",
          image: "/static/img/usually-item-04.png",
          name: "我的商品",
        },
      ],
      lon: "",
      lat: "",
    };
  },
  computed: {
    ...mapState([
      "vuex_user_id",
      "vuex_identity",
      "vuex_openid",
      "vuex_user_login",
      "vuex_power_01",
    ]),
  },
  watch: {
    vuex_identity(newVal) {
      let name = newVal ? "+发布" : "附近";
      uni.setTabBarItem({ index: 2, text: name });
    },
  },
  onLoad() {
    /* #ifdef H5 */
    this.lon = "116.90084";
    this.lat = "36.65142";
    this.getHomeClassifyList();
    // this.getHomeRecruitList();
    /* #endif */
    this.getHomeProductList();
    let homeName = this.vuex_identity ? "工作台" : "首页";
    let hallName = this.vuex_identity ? "+发布" : "附近";
    uni.setTabBarItem({ index: 0, text: homeName });
    uni.setTabBarItem({ index: 2, text: hallName });
    if (this.vuex_user_id) this.getUserInfo(1);
  },
  onShow() {
    if (this.vuex_user_id) this.getUserInfo(2);
    if (this.vuex_identity) {
      this.editLawyerLocation();
    } else {
      this.getLocationInfo();
    }
  },
  methods: {
    // 获取定位
    getLocationInfo() {
      let that = this;
      /* #ifdef MP-WEIXIN */
      uni.authorize({
        scope: "scope.userLocation",
        success() {
          uni.getLocation({
            type: "wgs84",
            success: (res) => {
              console.log(res);
              that.lon = res.longitude;
              that.lat = res.latitude;
              that.getHomeClassifyList();
              // that.getHomeRecruitList();
            },
          });
        },
        fail() {
          that.$t.locationPower();
        },
      });
      /* #endif */
    },
    // 修改律师定位
    editLawyerLocation() {
      let that = this;
      /* #ifdef MP-WEIXIN */
      uni.authorize({
        scope: "scope.userLocation",
        success(res) {
          uni.getLocation({
            type: "wgs84",
            success: (res) => {
              let data = {
                lvs_id: that.vuex_user_id,
                lon: res.longitude,
                lat: res.latitude,
              };
              that.lon = res.longitude;
              that.lat = res.latitude;
              that.$api.editLawyerLocation(data).then(() => {
                that.getHomeClassifyList();
                // that.getHomeRecruitList();
              });
            },
          });
        },
        fail() {
          that.$t.locationPower();
        },
      });
      /* #endif */
    },
    // 选择位置
    chooseLocation() {
      uni.chooseLocation({
        success: (res) => {
          let locationObj = this.formatLocation(res);
          // console.log(locationObj);
          this.location = `${locationObj.REGION_PROVINCE} ${locationObj.REGION_CITY} ${locationObj.REGION_COUNTRY}`;
        },
      });
    },
    // 分类
    getHomeClassifyList() {
      uni.showLoading({
        title: "加载中...",
      });
      this.$api
        .getHomeClassifyList({
          lon: this.lon,
          lat: this.lat,
        })
        .then((res) => {
          console.log(res);
          let data = res;
          if (!this.refresh) return uni.hideLoading();
          data.document_square.forEach((item) => {
            if (item.num >= 10000) {
              item.num = (item.num / 10000).toFixed(1) + "万";
            }
          });
          this.documentList1 = data.document_square.slice(0, 2);
          this.documentList2 = data.document_square.slice(2);
          let noticeList = [];
          data.demand_release.forEach((item) => {
            let object = {
              createtime: item.createtime,
              name: `${item.name.substr(0, 1) + "**"}已支付${
                item.money
              }元咨询费`,
            };
            noticeList.push(object);
          });
          setTimeout(() => {
            this.noticeList = noticeList;
          }, 100);
          this.refresh = false;
        });
      uni.hideLoading();
    },
    //
    recruiClassifyChange(id) {
      this.getHomeRecruitList(id);
    },
    // 招聘列表
    getHomeRecruitList(id) {
      let data = {
        recruit_id: id || "",
        lon: this.lon,
        lat: this.lat,
      };
      this.$api.getHomeRecruitList(data).then((res) => {
        console.log(res);
        this.recruitList = res || [];
      });
    },
    // 产品列表
    getHomeProductList() {
      this.$api.getHomeProductList({ page: this.page }).then((res) => {
        console.log(res);
        this.productList = [...this.productList, ...res];
      });
    },
    // 获取用户信息
    getUserInfo(type) {
      this.$api
        .getUserInfo({
          user_id: this.vuex_user_id,
        })
        .then((res) => {
          // console.log(res);
          this.userInfo = res;
          this.$u.vuex("vuex_identity", res.is_lvs == 1 ? 1 : 0);
          this.$u.vuex("vuex_power_01", res.rez_j.one);
          this.$u.vuex("vuex_power_02", res.rez_j.two);
          this.$u.vuex("vuex_power_03", res.rez_j.three);
          this.$u.vuex("vuex_power_04", res.rez_j.four);
          if (type == 1) {
            if (res.is_lvs && !res.rez_j.four) {
              this.$t.modal(
                "提示",
                "您已选择律师身份，未进行职业认证。",
                true,
                "认证",
                "",
                (res) => {
                  if (res) {
                    uni.navigateTo({
                      url: "/pages/subpackages/mine/authen/index",
                    });
                  } else {
                    // uni.navigateBack({ delta: 1 });
                  }
                }
              );
            }
          } else {
            this.getSecretKey(res);
          }
        });
    },
    // 获取秘钥
    getSecretKey(userinfo) {
      this.$api
        .getSecretKey({
          user_id: this.vuex_user_id,
        })
        .then((res) => {
          let userInfo = {
            userId: this.vuex_user_id.toString(),
            userSig: res.toString(),
            avatarUrl: userinfo.avatar.toString(),
            nickName: userinfo.nickname.toString(),
          };
          let promise = this.tim.login({
            userID: userInfo.userId,
            userSig: userInfo.userSig,
          });
          promise
            .then((res) => {
              // console.log(res);
              this.$u.vuex("vuex_user_info", userInfo);
              this.$store.commit("toggleIsLogin", true);
              setTimeout(() => {
                this.updateTim(userInfo);
              }, 200);
            })
            .catch((error) => {
              console.log(error);
            });
        });
    },
    // 更新TIM信息
    updateTim(userinfo) {
      let promise = this.tim.updateMyProfile({
        nick: userinfo.nickName,
        avatar:
          userinfo.avatarUrl ||
          "https://lvs.shandongweipai.com/uploads/20211026/d51d9b72b8884a240de555441dc6e708.jpg",
        gender: this.$TIM.TYPES.GENDER_MALE,
        selfSignature: "我的个性签名",
        allowType: this.$TIM.TYPES.ALLOW_TYPE_ALLOW_ANY,
      });
      promise
        .then((res) => {
          // console.log(res);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    formatLocation(res) {
      console.log(res);
      var regex =
        /^(北京市|天津市|重庆市|上海市|香港特别行政区|澳门特别行政区)/;
      var REGION_PROVINCE = [];
      var addressBean = {
        REGION_PROVINCE: null,
        REGION_COUNTRY: null,
        REGION_CITY: null,
        ADDRESS: null,
      };
      // 定位信息
      function regexAddressBean(address, addressBean) {
        // regex = /^(.*?[市州]|.*?地区|.*?特别行政区)(.*?[市区县])(.*?)$/g;
        regex = /^(.*?[市]|.*?地区|.*?特别行政区)(.*?[市区县])(.*?)$/g;
        var addxress = regex.exec(address);
        addressBean.REGION_CITY = addxress[1];
        addressBean.REGION_COUNTRY = addxress[2];
        addressBean.ADDRESS = addxress[3] + "(" + res.name + ")";
        // console.log(addxress);
      }
      if (!(REGION_PROVINCE = regex.exec(res.address))) {
        regex = /^(.*?(省|自治区))(.*?)$/;
        REGION_PROVINCE = regex.exec(res.address);
        addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
        regexAddressBean(REGION_PROVINCE[3], addressBean);
      } else {
        addressBean.REGION_PROVINCE = REGION_PROVINCE[1];
        regexAddressBean(res.address, addressBean);
      }
      return addressBean;
    },
  },
  onReachBottom() {
    if (this.page * this.pagesize > this.productList.length)
      return (this.status = "nomore");
    this.status = "loading";
    this.page = ++this.page;
    setTimeout(() => {
      this.getHomeProductList();
      if (this.page * this.pagesize > this.productList.length)
        this.status = "nomore";
      else this.status = "loading";
    }, 500);
  },
};
</script>

<style lang="scss" scoped>
</style>
